package logger

import (
	"fmt"
	"github.com/petermattis/goid"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type CustomTextFormatter struct {
}

func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	timestamp := entry.Time.Format("2006-01-02 15:04:05.000")
	level := entry.Level.String()
	message := entry.Message
	goroutineId := goid.Get()
	// 创建日志文件
	logLine := fmt.Sprintf("[%s] [%s] [go-%d] %s\n", strings.ToUpper(level), timestamp, goroutineId, message)
	return []byte(logLine), nil
}

// TimestampedLogger 当前验证还有问题，带补充
type TimestampedLogger struct {
	*lumberjack.Logger
}

func (tl *TimestampedLogger) Rotate() error {
	logrus.Info("开始执行日志轮转...")

	// 执行原始轮转
	if err := tl.Logger.Rotate(); err != nil {
		logrus.Errorf("原始轮转失败: %v", err)
		return err
	}

	// 等待压缩完成（关键！）
	time.Sleep(300 * time.Millisecond)

	// 获取压缩文件路径
	source := tl.Filename + ".gz"
	if _, err := os.Stat(source); os.IsNotExist(err) {
		logrus.Warnf("压缩文件不存在: %s", source)
		return nil
	}

	// 生成精确时间戳格式
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)

	// 构建新路径
	dest := filepath.Join(
		filepath.Dir(tl.Filename),
		"app-"+timestamp+".log.gz",
	)

	// 重命名文件
	if err := os.Rename(source, dest); err != nil {
		logrus.Errorf("重命名失败: %v", err)
		return err
	}

	logrus.Infof("轮转成功: %s → %s", source, dest)
	return nil
}

func InitLogConfig(logConfig LogConfigInter) {
	// 格式化输出
	logrus.SetLevel(logrus.InfoLevel)
	logFormat := &CustomTextFormatter{}
	logrus.SetFormatter(logFormat)
	config := logConfig.GetConfig()
	logFileConfig := &TimestampedLogger{
		Logger: config,
	}
	logrus.SetOutput(logFileConfig)
}

func Info(args ...interface{}) {
	logrus.Info(args...)
}

func Warn(args ...interface{}) {
	logrus.Warn(args...)
}

func Error(args ...interface{}) {
	logrus.Error(args...)
}

func Debug(args ...interface{}) {
	logrus.Debug(args...)
}

func Trace(args ...interface{}) {
	logrus.Trace(args...)
}

func Println(args ...interface{}) {
	logrus.Println(args...)
}

func Infof(format string, args ...interface{}) {
	logrus.Infof(format, args...)
}

func Warnf(format string, args ...interface{}) {
	logrus.Warnf(format, args...)
}

func Errorf(format string, args ...interface{}) {
	logrus.Errorf(format, args...)
}

func Debugf(format string, args ...interface{}) {
	logrus.Debugf(format, args...)
}

func Tracef(format string, args ...interface{}) {
	logrus.Tracef(format, args...)
}

func Printf(format string, args ...interface{}) {
	logrus.Printf(format, args...)
}
